package com.shuda.business.channel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.channel.dto.UpstreamChannelDTO;
import com.shuda.business.channel.dto.UpstreamChannelQueryDTO;
import com.shuda.business.channel.entity.UpstreamChannelEntity;
import com.shuda.business.channel.mapper.UpstreamChannelMapper;
import com.shuda.business.channel.service.UpstreamChannelService;
import com.shuda.common.dto.PageDTO;
import com.shuda.common.dto.PageResult;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 上游渠道服务实现类
 */
@Service
public class UpstreamChannelServiceImpl extends ServiceImpl<UpstreamChannelMapper, UpstreamChannelEntity> 
        implements UpstreamChannelService {

    @Autowired
    private UpstreamChannelMapper upstreamChannelMapper;

    @Override
    public PageResult<UpstreamChannelDTO> getUpstreamChannelPage(PageDTO pageDTO, UpstreamChannelQueryDTO queryDTO) {
        Page<UpstreamChannelEntity> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        
        LambdaQueryWrapper<UpstreamChannelEntity> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(queryDTO.getChannelName())) {
            wrapper.like(UpstreamChannelEntity::getChannelName, queryDTO.getChannelName());
        }
        
        if (StringUtils.hasText(queryDTO.getChannelCode())) {
            wrapper.eq(UpstreamChannelEntity::getChannelCode, queryDTO.getChannelCode());
        }
        
        if (StringUtils.hasText(queryDTO.getChannelType())) {
            wrapper.eq(UpstreamChannelEntity::getChannelType, queryDTO.getChannelType());
        }
        
        if (StringUtils.hasText(queryDTO.getChannelStatus())) {
            wrapper.eq(UpstreamChannelEntity::getChannelStatus, queryDTO.getChannelStatus());
        }
        
        if (queryDTO.getStartTime() != null) {
            wrapper.ge(UpstreamChannelEntity::getCreateTime, queryDTO.getStartTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            wrapper.le(UpstreamChannelEntity::getCreateTime, queryDTO.getEndTime());
        }
        
        wrapper.orderByDesc(UpstreamChannelEntity::getCreateTime);
        
        IPage<UpstreamChannelEntity> result = upstreamChannelMapper.selectPage(page, wrapper);
        
        List<UpstreamChannelDTO> dtoList = result.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return new PageResult<>(dtoList, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    public UpstreamChannelDTO getUpstreamChannelById(Long id) {
        UpstreamChannelEntity entity = upstreamChannelMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("上游渠道不存在");
        }
        return convertToDTO(entity);
    }

    @Override
    public Long createUpstreamChannel(UpstreamChannelDTO dto) {
        UpstreamChannelEntity entity = convertToEntity(dto);
        entity.setChannelStatus("enabled");
        entity.setCreateBy(SecurityUtils.getCurrentUsername());
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        entity.setDeleted(0);
        
        upstreamChannelMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateUpstreamChannel(Long id, UpstreamChannelDTO dto) {
        UpstreamChannelEntity existingEntity = upstreamChannelMapper.selectById(id);
        if (existingEntity == null) {
            throw new BusinessException("上游渠道不存在");
        }
        
        UpstreamChannelEntity entity = convertToEntity(dto);
        entity.setId(id);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        
        upstreamChannelMapper.updateById(entity);
    }

    @Override
    public void deleteUpstreamChannel(Long id) {
        UpstreamChannelEntity entity = upstreamChannelMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("上游渠道不存在");
        }
        
        entity.setDeleted(1);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        upstreamChannelMapper.updateById(entity);
    }

    @Override
    public void batchDeleteUpstreamChannel(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            List<UpstreamChannelEntity> entities = upstreamChannelMapper.selectBatchIds(ids);
            String currentUsername = SecurityUtils.getCurrentUsername();
            LocalDateTime now = LocalDateTime.now();
            
            for (UpstreamChannelEntity entity : entities) {
                entity.setDeleted(1);
                entity.setUpdateBy(currentUsername);
                entity.setUpdateTime(now);
                upstreamChannelMapper.updateById(entity);
            }
        }
    }

    @Override
    public void updateUpstreamChannelStatus(Long id, String status) {
        UpstreamChannelEntity entity = upstreamChannelMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("上游渠道不存在");
        }
        
        entity.setChannelStatus(status);
        entity.setUpdateBy(SecurityUtils.getCurrentUsername());
        entity.setUpdateTime(LocalDateTime.now());
        upstreamChannelMapper.updateById(entity);
    }

    @Override
    public List<UpstreamChannelDTO> getEnabledUpstreamChannelList() {
        LambdaQueryWrapper<UpstreamChannelEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UpstreamChannelEntity::getChannelStatus, "enabled")
                .eq(UpstreamChannelEntity::getDeleted, 0)
                .orderByDesc(UpstreamChannelEntity::getPriority)
                .orderByDesc(UpstreamChannelEntity::getCreateTime);
        
        List<UpstreamChannelEntity> entities = upstreamChannelMapper.selectList(wrapper);
        return entities.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    private UpstreamChannelDTO convertToDTO(UpstreamChannelEntity entity) {
        UpstreamChannelDTO dto = new UpstreamChannelDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    private UpstreamChannelEntity convertToEntity(UpstreamChannelDTO dto) {
        UpstreamChannelEntity entity = new UpstreamChannelEntity();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }
}